package com.gongsir.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.gongsir.entity.User;
import com.gongsir.entity.UserExample;
import com.gongsir.mapper.UserMapper;
import com.gongsir.service.UserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author 龚涛
 * @date 2020/8/17 16:03
 * 编码不要畏惧变化，要拥抱变化
 */
@Service("userService")
public class UserServiceImpl implements UserService {

    /**
     * 自动注入userMapper接口, spring帮助我们创建实现
     */
    @Resource
    private UserMapper userMapper;

    @Override
    public User getUserByUsername(String username) {
        // 调用db接口方法,查询user并返回
        UserExample example = new UserExample();
        example.createCriteria().andUsernameEqualTo(username);
        List<User> users = userMapper.selectByExample(example);
        if (users.size() == 1) {
            return users.get(0);
        }
        return null;
    }

    @Override
    public PageInfo<User> getAllUser(String keywords, int page, int size, String orderBy) {
        UserExample example = new UserExample();
        UserExample.Criteria criteria = example.createCriteria();
        if (null == keywords || "".equals(keywords)) {
            example = null;
        } else {
            criteria.andUsernameLike("%"+keywords+"%");
        }
        PageHelper.startPage(page,size,orderBy);
        List<User> users = userMapper.selectByExample(example);
        return new PageInfo<>(users);
    }

    @Override
    public int deleteUserById(int id) {
        return userMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int updateUser(User user) {
        return userMapper.updateByPrimaryKeySelective(user);
    }

    @Override
    public int saveUser(User user) {
        return userMapper.insertSelective(user);
    }
}
